import pymysql
from lib.config import config
from lib.logger import Logger

class sqlconn(object):
    logger = Logger()
    def __init__(self,host=None,port=None,user=None,password=None,database=None):
        self.param={
            "host":config["mysql"]["host"] if host is None else host ,
            "port":int(config["mysql"]["port"]) if port is None else port,
            "user":config["mysql"]["user"] if user is None else user,
            "password":config["mysql"]["password"] if password is None else password,
            "database":config["mysql"]["database"] if database is None else database
        }

    ## sql查询
    def sql_select(self,sql):
        with pymysql.connect(**self.param) as conn:
            with conn.cursor() as cursor:
                self.logger.debug(f"select查询sql为：{sql}")
                return cursor.execute(sql)

    ## sql增删改
    def sql_execute(self,sql_list):
        with pymysql.connect(**self.param) as conn:
            with conn.cursor() as cursor:
                try:
                    for sql in sql_list:
                        self.logger.debug(f"execute查询sql为：{sql}")
                        cursor.execute(sql)
                except Exception as e:
                    self.logger.error(e)
                    conn.rollback()
                else:
                    conn.commit()
                    self.logger.info("sql-commit完成")



